package conqueror.com.systemupdate.fragment;


import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;

import conqueror.com.systemupdate.R;
import conqueror.com.systemupdate.bean.NetBean;
import conqueror.com.systemupdate.config.Contans;
import conqueror.com.systemupdate.download.DownloadInfo;
import conqueror.com.systemupdate.download.DownloadManager;
import conqueror.com.systemupdate.download.DownloadState;
import conqueror.com.systemupdate.download.DownloadViewHolder;
import conqueror.com.systemupdate.util.NetSpeed;
import conqueror.com.systemupdate.util.PreferenceUtils;
import conqueror.com.systemupdate.util.RecoverUpdateUtil;

public class OnlineDownloadFragment extends Fragment {

    private ListView mLvDownload;

    private DownloadManager downloadManager;
    private DownloadListAdapter downloadListAdapter;
    private NetSpeed speed;
    private Handler mHandler;
    private TextView mShowUpdateInfo;

    private String TAG = OnlineDownloadFragment.class.getName();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_online_download, container, false);
        mLvDownload = (ListView) view.findViewById(R.id.lv_download);
        mShowUpdateInfo = (TextView) view.findViewById(R.id.tv_showUpdateInfo);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        PreferenceUtils.putString(getActivity(), "Fragment", "OnlineDownloadFragment");
        downloadManager = DownloadManager.getInstance();
        downloadListAdapter = new DownloadListAdapter();
        mLvDownload.setAdapter(downloadListAdapter);
        new Thread(new Runnable() {
            @Override
            public void run() {
                loadNetDate();
            }
        }).start();
    }

    /**
     * 检查显示更新信息
     */
    private void loadNetDate() {
        //按下后联网检查，是否有更新的系统
        RequestParams requestParams = new RequestParams(Contans.LOAD_URL);
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                NetBean netBean = gson.fromJson(result, NetBean.class);
                NetBean.OtaBean ota = netBean.ota;
                mShowUpdateInfo.setText(ota.context);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mShowUpdateInfo.setText("网络出错，请取消后重试！");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private class DownloadListAdapter extends BaseAdapter {
        private Context mContext;
        private final LayoutInflater mInflater;

        private DownloadListAdapter() {
            mContext = getActivity().getBaseContext();
            mInflater = LayoutInflater.from(mContext);

        }

        @Override
        public int getCount() {
            if (downloadManager == null) return 0;
            return downloadManager.getDownloadListCount();
        }

        @Override
        public Object getItem(int i) {
            return downloadManager.getDownloadInfo(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            DownloadItemViewHolder holder = null;
            DecimalFormat df = new DecimalFormat("###.00");
            DownloadInfo downloadInfo = downloadManager.getDownloadInfo(i);
            if (view == null) {
                view = mInflater.inflate(R.layout.download_item, null);
                holder = new DownloadItemViewHolder(view, downloadInfo);
                view.setTag(holder);
                holder.refresh();
            } else {
                holder = (DownloadItemViewHolder) view.getTag();
                holder.update(downloadInfo);
            }

            if (downloadInfo.getState().value() < DownloadState.FINISHED.value()) {
                try {
                    downloadManager.startDownload(
                            downloadInfo.getUrl(),
                            downloadInfo.getLabel(),
                            downloadInfo.getFileSavePath(),
                            downloadInfo.getFileContent(),
                            downloadInfo.isAutoResume(),
                            downloadInfo.isAutoRename(),
                            holder);
                } catch (DbException ex) {
                    Toast.makeText(x.app(), "添加下载失败", Toast.LENGTH_LONG).show();
                }
            } else {
                holder.mTvDownloadFileSize.setText("文件大小:" + df.format(downloadInfo.getFileLength() / 1048576.0) + "M");
                holder.mTvDownloadSize.setText("下载进度:100%");
                holder.mTvDownloadSpeed.setText("下载速度:0kb/s");
            }

            return view;
        }
    }

    public class DownloadItemViewHolder extends DownloadViewHolder {
        @ViewInject(R.id.tv_downloadedSize)
        TextView mTvDownloadSize;

        @ViewInject(R.id.tv_downloadSpade)
        TextView mTvDownloadSpeed;

        @ViewInject(R.id.tv_downloadFileSize)
        TextView mTvDownloadFileSize;

        @ViewInject(R.id.tv_newSystemVersion)
        TextView mTvNewSystemVersion;

        @ViewInject(R.id.download_pb)
        ProgressBar progressBar;
        @ViewInject(R.id.download_stop_btn)
        Button stopBtn;
        DecimalFormat df = new DecimalFormat("###.00");

        public DownloadItemViewHolder(View view, DownloadInfo downloadInfo) {
            super(view, downloadInfo);
            refresh();
        }

        @Event(R.id.download_stop_btn)
        private void toggleEvent(View view) {
            DownloadState state = downloadInfo.getState();
            switch (state) {
                case WAITING:
                case STARTED:
                    downloadManager.stopDownload(downloadInfo);
                    break;
                case ERROR:
                case STOPPED:
                    try {
                        downloadManager.startDownload(
                                downloadInfo.getUrl(),
                                downloadInfo.getLabel(),
                                downloadInfo.getFileSavePath(),
                                downloadInfo.getFileContent(),
                                downloadInfo.isAutoResume(),
                                downloadInfo.isAutoRename(),
                                this);
                    } catch (DbException ex) {
                        Toast.makeText(x.app(), "添加下载失败", Toast.LENGTH_LONG).show();
                    }
                    break;
                case FINISHED:
                    File file = new File(downloadInfo.getFileSavePath());
                    if (!file.exists()) {
                        Toast.makeText(getActivity(), "文件不存在,请重新下载", Toast.LENGTH_SHORT).show();
                        downloadInfo.setState(DownloadState.ERROR);
                        refresh();
                        downloadListAdapter.notifyDataSetChanged();
                    } else {
                        //下载完成点击安装系统
                        try {
                            Log.e("OnLineDownloadFragment", "--filePath---" + downloadInfo.getFileSavePath() + "-=-=-=" + downloadInfo.getLabel());
                            PreferenceUtils.putString(getActivity(), "Fragment", "OnlineCheckFragment");
                            RecoverUpdateUtil.getInstance((PowerManager) getActivity().
                                    getSystemService(Context.POWER_SERVICE)).
                                    bootCommand("--update_package=" + downloadInfo.getFileSavePath(), "--locale=zh_CN");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    break;
                default:
                    break;
            }
        }

        @Event(R.id.download_remove_btn)
        private void removeEvent(View view) {
            showDialog(downloadInfo);
        }

        @Override
        public void update(DownloadInfo downloadInfo) {
            super.update(downloadInfo);
            refresh();
        }

        @Override
        public void onWaiting() {
            refresh();
        }

        @Override
        public void onStarted() {
            refresh();
        }

        @Override
        public void onLoading(long total, long current) {
            double t = total / 1048576.0;
            double c = current / 1048576.0;

            NumberFormat instance = NumberFormat.getInstance();
            instance.setMaximumFractionDigits(2);
            String format = instance.format((c / t) * 100);
            String format1 = instance.format(t);

            mTvDownloadFileSize.setText("文件大小:" + format1 + "M");
            mTvDownloadSize.setText("下载进度:" + format + "%");
//            size.setText(df.format(t) + "MB/" + df.format(c) + "MB");
            refresh();
        }

        @Override
        public void onSuccess(File result) {
            refresh();
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            refresh();
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {
            refresh();
        }

        public void refresh() {
            showNetSpeed(mTvDownloadSpeed);//显示速度
            progressBar.setProgress(downloadInfo.getProgress());
            mTvNewSystemVersion.setText("新固件版本:" + downloadInfo.getLabel());
            stopBtn.setText(x.app().getString(R.string.pause));
            DownloadState state = downloadInfo.getState();
            switch (state) {
                case WAITING:
                case STARTED:
                    stopBtn.setText(x.app().getString(R.string.pause));
                    break;
                case ERROR:
                    stopBtn.setText("重新下载");
                    break;
                case STOPPED:
                    stopBtn.setText(x.app().getString(R.string.start));
                    break;
                case FINISHED:
                    stopBtn.setText("更新系统");
                    break;
                default:
                    stopBtn.setText(x.app().getString(R.string.start));
                    break;
            }
        }
    }

    /**
     * 显示下载的网速
     *
     * @param textView
     */
    private void showNetSpeed(final TextView textView) {
        try {
            mHandler = new Handler() {

                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == 1) {
                        textView.setText("下载速度:" + msg.arg1 + "kb/s");
                    }
                    super.handleMessage(msg);
                }

            };
            speed = new NetSpeed(getContext(), mHandler);
            speed.startCalculateNetSpeed();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (speed != null) {
            speed.stopCalculateNetSpeed();
            speed = null;
        }
//        PreferenceUtils.putString(getActivity(), "Fragment", "OnlineDownloadFragment");
    }

    /**
     * dialog确定取消或者不取消
     */
    private void showDialog(final DownloadInfo downloadInfo) {
        //挂载View并初始化
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View localView = inflater.inflate(R.layout.local_dialog, (ViewGroup) getView().findViewById(R.id.local_dialog_parent));
        Button btnEnsure = (Button) localView.findViewById(R.id.bt_localDialogOK);
        TextView tvDialogMessage = (TextView) localView.findViewById(R.id.tv_dialogMessage);
        Button btnCancel = (Button) localView.findViewById(R.id.bt_localDialogCancel);
        tvDialogMessage.setText("此操作会删除已下载的数据\n是否放弃本次下载？");

        //获取biulder
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        //将自己的view设置到dialog上
        final AlertDialog dialog = builder.setView(localView).create();
        dialog.setCanceledOnTouchOutside(false);//点击dialog以外而不是去焦点
//        dialog.setCancelable(false);//按back键也是没有用的
        dialog.show();

        //自定义的确定按钮
        btnEnsure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                //返回原来的fragment
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction transaction = fragmentManager.beginTransaction();
                OnlineCheckFragment onlineCheckFragment = new OnlineCheckFragment();
                transaction.replace(R.id.fl_onlineContainer, onlineCheckFragment);
                transaction.commit();
                //删除下载的文件
                ensureClick(downloadInfo);
            }
        });
        //自定义取消按钮
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    /**
     * dialog确定时候的操作
     */
    private void ensureClick(DownloadInfo downloadInfo) {
        try {
            downloadManager.removeDownload(downloadInfo);
            downloadListAdapter.notifyDataSetChanged();
        } catch (DbException e) {
            Toast.makeText(x.app(), "移除任务失败", Toast.LENGTH_LONG).show();
        }

        //删除临时文件
        File f = new File("/sdcard");
        File[] files = f.listFiles();// 列出所有文件
        // 将所有文件存入list中
        if (files != null) {
            int count = files.length;// 文件个数
            Log.e(TAG, "-------sdcard---count-------" + count);
            for (int j = 0; j < count; j++) {
                File file = files[j];
                if (file.getName().endsWith(".tmp")) {
                    //删除文件
                    File filee = new File(downloadInfo.getFileSavePath() + ".tmp");
                    if (filee.exists()) {
                        filee.delete();
                    }
                }
            }
        }

        //删除文件
        File file = new File(downloadInfo.getFileSavePath());
        if (file.exists()) {
            file.delete();
        }

    }


}
